package cn.aib.eduservice.controller;


import cn.aib.commonutils.R;
import cn.aib.eduservice.client.VodClient;
import cn.aib.eduservice.entity.EduVideo;
import cn.aib.eduservice.service.EduVideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-12-21
 */
@RestController
@RequestMapping("/eduservice/video")
//@CrossOrigin
@Slf4j
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private VodClient vodClient;

    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        //添加小节
        boolean flag = eduVideoService.save(eduVideo);

        if(flag){
            return R.ok();
        }else {
            return R.error();
        }

    }

    //删除小节
    @DeleteMapping("deleteVideo/{videoId}")
    public R deleteVideo(@PathVariable String videoId){
        /**
         *  删除视频
         *      根据小节ID查询小节，得到视频ID，再删除视频
         */
        log.info("删除的小节ID："+videoId);

        EduVideo video = eduVideoService.getById(videoId);

        String videoSourceId = video.getVideoSourceId();

        //视频ID存在，根据视频ID删除视频
        if(!StringUtils.isEmpty(videoSourceId)){
            vodClient.deleteVideoById(videoSourceId);
            log.info("视频删除了");
        }

        //删除小节
        boolean flag = eduVideoService.removeById(videoId);
        if(flag){
            return R.ok();
        }else {
            return R.error();
        }

    }

    //修改小节
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo video){
        //添加小节
        boolean flag = eduVideoService.updateById(video);
        if(flag){
            return R.ok();
        }else {
            return R.error();
        }
    }

    //查询小节
    @GetMapping("getVideoById/{videoId}")
    public R getVideoById(@PathVariable String videoId){
        EduVideo video = eduVideoService.getById(videoId);

        return R.ok().data("video",video);
    }
}

